<?php
namespace Todo\Model\Sys;

use Todo\Model\BaseModel;
use Todo\Service\LoginService;
use Org\Util\String;

class UserModel extends BaseModel
{
    public $tableName = 'sys_user';

    public $_validate = array(
        array('account', 'require', '请输入用户账号',0),
        array('account','2,50','账号长度超出限制！',0,'length'),
        array('account','','账号已经存在！',0,'unique',1),
        array('nickname', 'require', '请输入用户昵称'),
        array('email', 'email', '请输入用户邮箱'),
        array('mobile', '11,11', '请输入有效的手机号码',0,'length')
    );

    protected $_auto = array(
        array('photo', '', self::MODEL_INSERT),
        array('is_del', 0, self::MODEL_INSERT),
        array('create_time', 'auto_datetime', self::MODEL_INSERT, 'function'),
        array('update_time', 'auto_datetime', self::MODEL_BOTH, 'function'),
        array('password', '_password', self::MODEL_INSERT, 'callback'),
        array('salt', '_salt', self::MODEL_INSERT, 'callback'),
        array('tnt_id', 'auto_tnt', self::MODEL_INSERT, 'function')
    );
    
    protected function _salt(){
        if(!$this->salt) $this->salt =  String::randString(6);
        return $this->salt;
    }
    protected function _password(){
        $this->_salt();
        $password = I('post.password');
        if(!$password) $password = md5(C('DEFAULT_PASSWORD').C('MD5_SALT'));
        return LoginService::getInstance()->encrypt($password,  $this->salt);
    }

    /**
     * 添加角色
     * @param $userId
     * @param $idenId
     * @param $param
     */
    public function addIdentity($userId, $idenId, $param){
        $UserIdentity = D('Todo/Sys/UserIdentity');
        $info = $UserIdentity->where(array('user_id'=>$userId, 'iden_id'=>$idenId))->find();
        if($info){
            $info['param'] = $param;
            return $UserIdentity->save($info);
        }else{
            $idenInfo = D('Todo/Sys/Identity')->keyFind($idenId);
            if(!$idenInfo) return false;

            $roleInfo = array('user_id'=>$userId, 'role_id'=>$idenInfo['role_id']);
            if(D('Todo/Sys/UserRole')->find($roleInfo)) D('Todo/Sys/UserRole')->insert($roleInfo);

            $info = array(
                'user_id'=>$userId,
                'iden_id'=>$idenId,
                'param' => $param
            );
            return $UserIdentity->add($info);
        }
    }

    /**
     * 更新用户的角色和身份
     * @param int $id 用户ID
     * @param mixed $roleIds 角色
     */
    protected function changeRole($id, $roleIds){
        $sql = 'DELETE FROM sys_user_role WHERE user_id = '.$id;
        $this->execute($sql);

        if(empty($roleIds)) return;

        if(is_array($roleIds)) $roleIds = implode(',', $roleIds);
        $sql = 'INSERT INTO sys_user_role(user_id, role_id) (SELECT '. $id.',id FROM sys_role WHERE status=1 AND id IN ('. $roleIds. '))';
        $this->execute($sql);
    }

    /**
     * 添加用户完成后操作
     * @param $data
     * @param $options
     */
    protected function _after_insert($data,$options) {
        $roles = I('post.role_id');
        if($roles) $this->changeRole($data['id'], $roles);

        $idenId = I('post.iden_id');
        if($idenId)  $this->addAll($data['id'], $idenId, I('post.iden_param'));

        $status = array(
            'user_id' => $data['id'],
            'login_count' => 0,
            'last_time' => 0,
            'last_ip' => ''
        );
        D('Todo/Sys/UserStatus')->insert($status);
    }

    protected function _after_update($data,$options) {
        $roles = I('post.role_id');
        if($roles) $this->changeRole($data['id'], $roles);

        $idenId = I('post.iden_id');
        if($idenId)  $this->addAll($data['id'], $idenId, I('post.iden_param'));

    }
}